import {moveDelta, notAllowTilesetURls} from '../config/env'
import FlatTilesetTool from './flattilesettool.js'

export default class ModelUtils {

    constructor(bus) {
        this.bus = bus;
        const {Cesium, cesiumViewer} = window;
        this.ptHandler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.scene.canvas);
        // this.selected = {
        //     feature: undefined,
        //     originalColor: new Cesium.Color()
        // };
        this.lastX=this.lastY=0;
        this.isSilhouette = true;
        if(this.isSilhouette){
            this.silhouetteBlue = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
            this.silhouetteBlue.uniforms.color = Cesium.Color.LIME;//Cesium.Color.fromCssColorString('#ffe12a');
            this.silhouetteBlue.uniforms.length = 0.01;
            this.silhouetteBlue.selected = [];
            cesiumViewer.scene.postProcessStages.add(Cesium.PostProcessStageLibrary.createSilhouetteStage([this.silhouetteBlue]));
        }
        this.isRemoved = false;
        this.modelType='max';
        this.ldCollection = new Cesium.PrimitiveCollection();
        cesiumViewer.scene.primitives.add(this.ldCollection)
        this.lastPrimitive = null;
        this.lastColor = null;
        this.lastId = null;
        this.notAllowTilesetURls=[];
        this.flatTilesetTool = null;
    }


    removeFromScene(){
        //this.removeHandler();
        //this.bus.$emit('removemodelhandler');
        if(this.modelType == 'obq'){
            // this.modelType=null;
            // this.ldCollection.removeAll();
            if (this.lastPrimitive) {
                let attributes = this.lastPrimitive.getGeometryInstanceAttributes(this.lastId);
                attributes.color = this.lastColor;
                this.lastPrimitive = null;
                this.lastId = null;
            }
        }
        else{
            if(this.isSilhouette){
                this.silhouetteBlue.selected = [];
            }
        }



        this.lastX=this.lastY=0;

        this.isRemoved = true;

    }


    initModels(modelParams){
        const {Cesium, cesiumViewer} = window;
        modelParams.forEach(item => {
                let longitude = item.longitude;
                let latitude = item.latitude;
                let height = item.height;
                let heading = item.heading;
                let scale = new Cesium.Cartesian3(item.scale, item.scale, item.scale) ;
                let tileset = new Cesium.Cesium3DTileset({
                    allowPicking:false,
                    url: item.modelUrl,
                    maximumScreenSpaceError:item.maximumScreenSpaceError?item.maximumScreenSpaceError:16
                });
                cesiumViewer.scene.primitives.add(tileset);
                tileset.readyPromise.then( tileset=> {
                    let position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
                    let mat = Cesium.Transforms.eastNorthUpToFixedFrame(position);
                    let rotationX = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(heading)));
                    Cesium.Matrix4.multiply(mat, rotationX, mat);
                    let scaleMat = Cesium.Matrix4.fromScale(scale);
                    Cesium.Matrix4.multiply(mat, scaleMat, mat);
                    tileset._root.transform = mat;

                    if(!this.flatTilesetTool){
                        this.flatTilesetTool = new FlatTilesetTool({
                            tileset:tileset
                        });
                    }
                    if(item.digRegion){

                        let regionData = JSON.parse(item.digRegion);
                        this.fromDigRegionGeoJson(regionData);
                    }

                    // viewer.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height + 1000) });
                });
                 if(item.modelType && item.modelType== 'obq' && item.geojson){
                     let geoJsonData = JSON.parse(item.geojson);
                    this.fromGeoJson(geoJsonData);
                }

                 if(item.allowpick && item.allowpick==0){
                     this.notAllowTilesetURls.push(item.modelUrl);
                 }


        });

    }

    fromGeoJson(jsonData){
        for(let i=0; i<jsonData.features.length; i++){
            let coordinates = jsonData.features[i].geometry.coordinates[0];
            let arr = [];
            for(let j=0; j<coordinates.length; j++){
                arr.push(coordinates[j][0],coordinates[j][1]);
            }
            let polygonHierarchy = new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(arr)
            );
            let pid = jsonData.features[i].properties.featureId+'_'+jsonData.features[i].properties.featureName;
            this.addLdPrimitive1({
                hierarchy: polygonHierarchy,
                extrudedHeight: 50,
                id: pid
            });

        }
    }

    fromDigRegionGeoJson(regionData){
        this.flatTilesetTool.fromGeoJson(regionData);
    }

    addLdPrimitive1(e) {
        this.ldCollection.add(new Cesium.ClassificationPrimitive({
            geometryInstances: new Cesium.GeometryInstance({
                geometry: new Cesium.PolygonGeometry({
                    polygonHierarchy: e.hierarchy,
                    extrudedHeight: e.extrudedHeight
                }),
                attributes: {
                    color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(0, 1, 0, 0)),
                    show: new Cesium.ShowGeometryInstanceAttribute(true) //确定是否显示几何实例
                },
                id: e.id
            }),
            classificationType: Cesium.ClassificationType.BOTH,
            releaseGeometryInstances: false
        }))
    }
    addHandler() {
        const {Cesium, cesiumViewer} = window;

            this.ptHandler.setInputAction((movement) => {
                let foundPosition = false;
                if (!Cesium.defined(movement.endPosition)) return;
                if(Math.abs(this.lastX-movement.endPosition.x)<moveDelta && Math.abs(this.lastY-movement.endPosition.y)<moveDelta){
                    return;
                }

                let pickedObjectArr = cesiumViewer.scene.drillPick(movement.endPosition,2);
                if(Cesium.defined(pickedObjectArr)) {
                    let pickedObject = null;
                    for (let i =0; i < pickedObjectArr.length; i++) {
                        if (Cesium.defined(pickedObjectArr[i]) &&pickedObjectArr[i].primitive){
                            if (pickedObjectArr[i] instanceof Cesium.Cesium3DTileFeature) {
                                pickedObject = pickedObjectArr[i];
                                break;
                            }
                            else if(pickedObjectArr[i].primitive instanceof Cesium.ClassificationPrimitive) {
                                pickedObject = pickedObjectArr[i];
                                this.modelType = 'obq';
                                break;
                            }

                        }
                    }
                    for (let i = 0; i < notAllowTilesetURls.length; i++) {
                        if (Cesium.defined(pickedObject) ) {
                            if(pickedObject.primitive.url == notAllowTilesetURls[i]){
                                return;
                            }

                        }
                    }
                    if (pickedObject) {
                        let featureName = '';
                        if(this.modelType == 'obq'){
                            let attributes = pickedObject.primitive.getGeometryInstanceAttributes(pickedObject.id);
                            if (this.lastId != pickedObject.id) {
                                if (this.lastPrimitive) {
                                    let attributes = this.lastPrimitive.getGeometryInstanceAttributes(this.lastId);
                                    attributes.color = this.lastColor;
                                }
                                this.lastColor = [...attributes.color];
                                this.lastColor[3] = 0;
                                this.lastPrimitive = pickedObject.primitive;
                            }
                            this.lastId = pickedObject.id;
                            attributes.color = [attributes.color[0], attributes.color[1],
                                attributes.color[2], 128];



                            let pid = pickedObject.id;
                            let index = pid.indexOf('_');
                             featureName = pid.slice(index+1);

                        }
                        else{
                            if(this.isSilhouette){
                                if (this.silhouetteBlue.selected.length>0) {
                                    if (this.silhouetteBlue.selected[0] === pickedObject) return;
                                    this.silhouetteBlue.selected = [];
                                }
                                this.silhouetteBlue.selected = [pickedObject];
                            }


                             featureName = pickedObject.getProperty('name');


                        }
                        this.lastX=movement.endPosition.x;
                        this.lastY=movement.endPosition.y;
                        this.bus.$emit("tqmodelmouseover", {
                            name: featureName,
                            x: movement.endPosition.x,
                            y: movement.endPosition.y,
                            visible: true
                        });
                        foundPosition = true;
                        document.getElementById('cesiumDiv').style.cssText+=';cursor:pointer';

                    }


                }

                if (!foundPosition) {
                    document.getElementById('cesiumDiv').style.cssText+=';cursor:default';
                    if(this.modelType == 'obq') {
                        if (this.lastPrimitive) {
                            let attributes = this.lastPrimitive.getGeometryInstanceAttributes(this.lastId);
                            attributes.color = this.lastColor;
                            this.lastPrimitive = null;
                            this.lastId = null;

                        }
                    }
                    else {
                        if(this.isSilhouette){
                            if (this.silhouetteBlue.selected.length>0) {
                                this.silhouetteBlue.selected = [];
                            }
                        }
                    }
                    this.bus.$emit("tqmodelmouseout");
                }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    }

    removeHandler() {
        if (this.ptHandler && !this.ptHandler.isDestroyed()) {
            this.ptHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }
    }


    destoryHandler() {
        if (this.ptHandler && !this.ptHandler.isDestroyed()) {
            this.ptHandler.destroy();
        }
    }
}




